<?php


namespace app\admin\model;


use think\Db;
use think\Model;

class PushStoreRule extends Model
{
    protected $autoWriteTimestamp = true;
    public static function addUp($key,$sta,$val){

        switch ($sta){
            case "包含":
                if(!is_string($val))return "不是字符";
                break;
            case "小于":
            case "等于":
            case "大于":
                if (!is_numeric($val))return "不是数字";
                break;
            case "介于":
               if( !strpos($val,"~")) return "要包含~区分";
               $v = explode("~",$val);
               if(count($v)<2)return "填入格式错误~";
               if (!is_numeric($v[0]))return "说明需要数字";
               if (!is_numeric($v[1]))return "说明需要数字";
            default:
        }

        return "";
    }

    public static function list($title,$key,$staffNo)
    {
        $r = PushStoreRule::field("*,d.label as `key`,p.`id`,p.create_time")->alias("p")
            ->leftJoin("ic_dict d","d.value = p.`key` and cate = 'store_key'")
        ;
        if($title){
             $r->where("p.title","like","%$title%");
        }

        if($key){
            $r->where("p.key","like","%$key%");
        }

        if($staffNo){
            $r->where("p.staff_no",$staffNo);
        }

        $resN = $r->count();
        $res = $r->select();
        return listDate($res,$resN);
    }

    public static function add($title,$key,$sta,$val,$staffNo,$staffName)
    {
        $a = self::addUp($key,$sta,$val);
        if($a){
            return $a;
        }
        $p = PushStoreRule::field("id")->where("title",$title)->find();
        if($p){
            return "数据已经存在~";
        }
        PushStoreRule::create(["title"=>$title,"key"=>$key,"standard"=>$sta,"val"=>$val,"staff_no"=>$staffNo,"staff_name"=>$staffName]);
        return "";
    }

    public static function up($title,$key,$sta,$val,$staffNo,$id)
    {
        $a = self::addUp($key,$sta,$val);
        if($a){
            return $a;
        }
        $p = PushStoreRule::where("id",$id)->find();
        if(!$p)return "数据不存在~";
        if($p["staff_no"] != $staffNo)return "新增人员不相同~";
        PushStoreRule::where("id",$id)->data(["title"=>$title,"key"=>$key,"standard"=>$sta,"val"=>$val])->insert();
        return "";
    }

    public static function del($id)
    {
        $p = PushStoreRule::field("id")->where("id",$id)->find();
        if(!$p){
            return "数据不存在~";
        }
        $p->delete();
        return "";
    }

    public static function det($id)
    {
        return PushStoreRule::field("*")->where("id",$id)->find();
    }

    public static function incNum($title)
    {
        PushStoreRule::where("title",$title)->data(["num"=> Db::raw('num+1')])->Update();
    }
}